import axios from "axios";
import { message } from "antd";

import { createHashHistory } from "history";

import { prefixRoute, needToken } from "src/configs";

const history = createHashHistory();

//响应时间
// axios.defaults.timeout = 300000; // 5 min
axios.defaults.timeout = 1200000; // 20 min
axios.defaults.headers.post["Content-Type"] = "application/json";

// request interceptor
axios.interceptors.request.use(
	config => {
		config.headers["token"] = localStorage.getItem("token");
		return config;
	},
	error => {
		return Promise.reject(error);
	}
);
// response interceptor
axios.interceptors.response.use(
	response => {
		if (response.status >= 400) {
			// 未登录或token过期
			if (response.status === 401) {
				needToken && history.push(`${prefixRoute}/login`);
				return;
			}
			return Promise.reject(response);
		}
		return response;
	},
	error => {
		if (error.response.status === 401) {
			history.push(`${prefixRoute}/login`);
		}
		const err = error.response.data;
		message.error(err.message || err.error || err.path);
		return Promise.reject(error);
	}
);

export const get = (url, params, config = {}) => {
	return axios
		.get(url, {
			params: params,
			headers: {
				token: localStorage.getItem("token")
			},
			...config
		})
		.then(res => res.data);
};

export const post = (url, params, config = {}, otherheaders = {}) => {
	return axios
		.post(url, params, {
			headers: {
				token: localStorage.getItem("token"),
				...otherheaders
			},
			...config
		})
		.then(res => res.data);
};

export const postWithQuery = (url, params, query = {}, config = {}, otherheaders = {}) => {
	let queryStr = new URLSearchParams(query).toString();
	queryStr && (queryStr = "?" + queryStr);
	return axios
		.post(url + queryStr, params, {
			headers: {
				token: localStorage.getItem("token"),
				...otherheaders
			},
			...config
		})
		.then(res => res.data);
};

// get方式导出文件
export const getToFile = (url, params, config = {}) => {
    return axios.get(url, {
        params: params,
        headers: {
            token: localStorage.getItem('token'),
        },
        ...config,
    }).then(res => res);
};


export const postToFile = (url, params, config = {}, otherheaders = {}) => {
	return axios
		.post(url, params, {
			headers: {
				token: localStorage.getItem("token"),
				...otherheaders
			},
			...config
		})
		.then(res => res);
};


export const all = (iterable = []) => {
	return axios.all(iterable).then(
		axios.spread((acct, perms) => {
			// Both requests are now complete
			// console.log(acct, perms);
		})
	);
};

export default axios;
